<template>
  <div class="space-y-6">
    <!-- 页面标题 -->
    <div class="bg-white rounded-lg shadow p-6">
      <div class="flex items-center justify-between">
        <div>
          <h2 class="text-lg font-medium text-gray-900">{{ $t('dashboard.myPets') }}</h2>
          <p class="mt-1 text-sm text-gray-600">
            {{ $t('dashboard.description') }}
          </p>
        </div>
        <button
          @click="showAddPetModal = true"
          class="btn-primary"
        >
          {{ $t('pet.actions.add') }}
        </button>
      </div>
    </div>

    <!-- 宠物列表 -->
    <div class="bg-white rounded-lg shadow">
      <div v-if="loading" class="flex justify-center py-12">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
      </div>

      <div v-else-if="error" class="p-6">
        <div class="bg-red-50 border border-red-200 rounded-md p-4">
          <div class="flex">
            <ExclamationTriangleIcon class="h-5 w-5 text-red-400" />
            <div class="ml-3">
              <h3 class="text-sm font-medium text-red-800">{{ $t('error.loadFailed') }}</h3>
              <p class="mt-1 text-sm text-red-700">{{ error }}</p>
              <div class="mt-3">
                <button
                  @click="fetchPets"
                  class="text-sm bg-red-100 text-red-800 px-3 py-1 rounded hover:bg-red-200"
                >
                  {{ $t('common.retry') }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else-if="pets.length === 0" class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">还没有宠物信息</h3>
        <p class="mt-1 text-sm text-gray-500">
          添加您的宠物信息，方便快速发布寻宠信息
        </p>
        <div class="mt-6">
          <button
            @click="showAddPetModal = true"
            class="btn-primary"
          >
            添加第一只宠物
          </button>
        </div>
      </div>

      <div v-else class="p-6">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div
            v-for="pet in pets"
            :key="pet.id"
            class="bg-gray-50 rounded-lg p-4 hover:bg-gray-100 transition-colors cursor-pointer"
            @click="openPetDetail(pet)"
          >
            <!-- 宠物照片 -->
            <div class="aspect-square mb-3 rounded-lg overflow-hidden bg-gray-200 flex items-center justify-center">
              <img
                v-if="pet.photo_url"
                :src="getFullImageUrl(pet.photo_url)"
                :alt="pet.name"
                class="max-w-full max-h-full object-contain"
              />
              <svg
                v-else
                class="h-12 w-12 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
            </div>

            <!-- 宠物信息 -->
            <div>
              <h3 class="font-medium text-gray-900 mb-1">{{ pet.name || '未命名' }}</h3>
              <p class="text-sm text-gray-600 mb-2">
                {{ pet.species }} · {{ pet.color }}
                <span v-if="pet.breed"> · {{ pet.breed }}</span>
              </p>
              <div class="flex items-center justify-between text-xs text-gray-500">
                <span>{{ getGenderLabel(pet.gender) }}</span>
                <span v-if="pet.age">{{ pet.age }}岁</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="pagination.totalPages > 1" class="mt-6">
          <Pagination
            :current-page="pagination.page"
            :total-pages="pagination.totalPages"
            :total="pagination.total"
            @page-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 添加宠物模态框 -->
    <PetForm
      v-if="showAddPetModal"
      :show="showAddPetModal"
      @close="showAddPetModal = false"
      @success="handlePetAdded"
    />

    <!-- 宠物详情模态框 -->
    <PetDetailModal
      v-if="showDetailModal && selectedPet"
      :show="showDetailModal"
      :pet="selectedPet"
      @close="closeDetailModal"
      @updated="handlePetUpdated"
      @deleted="handlePetDeleted"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { petService } from '@/services/pets'
import { getFullImageUrl } from '@/utils/helpers'
import { PAGINATION } from '@/constants'
import { usePetGenderOptions } from '@/utils/i18n-options'
import Pagination from '@/components/Pagination.vue'
import PetForm from '@/components/PetForm.vue'
import PetDetailModal from '@/components/PetDetailModal.vue'
import type { Pet } from '@/types'

// 状态
const loading = ref(false)
const error = ref('')
const pets = ref<Pet[]>([])
const pagination = ref({
  page: 1,
  limit: PAGINATION.DEFAULT_LIMIT,
  total: 0,
  totalPages: 0,
})

// 模态框状态
const showAddPetModal = ref(false)
const showDetailModal = ref(false)
const selectedPet = ref<Pet | null>(null)

// 获取宠物列表
const fetchPets = async () => {
  try {
    loading.value = true
    error.value = ''

    const response = await petService.getMyPets({
      page: pagination.value.page,
      limit: pagination.value.limit,
    })

    if (response.success && response.data) {
      pets.value = response.data
      if (response.pagination) {
        pagination.value = {
          page: response.pagination.currentPage,
          limit: response.pagination.itemsPerPage,
          total: response.pagination.totalItems,
          totalPages: response.pagination.totalPages,
        }
      }
    } else {
      throw new Error(response.message || '获取宠物列表失败')
    }
  } catch (err) {
    console.error('获取宠物列表失败:', err)
    error.value = err instanceof Error ? err.message : '获取宠物列表失败'
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.page = page
  fetchPets()
}

// 打开宠物详情
const openPetDetail = (pet: Pet) => {
  selectedPet.value = pet
  showDetailModal.value = true
}

// 关闭宠物详情
const closeDetailModal = () => {
  showDetailModal.value = false
  selectedPet.value = null
}

// 处理宠物添加成功
const handlePetAdded = () => {
  showAddPetModal.value = false
  fetchPets()
}

// 处理宠物更新成功
const handlePetUpdated = (updatedPet: Pet) => {
  const index = pets.value.findIndex(p => p.id === updatedPet.id)
  if (index !== -1) {
    pets.value[index] = updatedPet
  }
  closeDetailModal()
}

// 处理宠物删除成功
const handlePetDeleted = (petId: number) => {
  pets.value = pets.value.filter(p => p.id !== petId)
  closeDetailModal()
}

// 国际化选项
const petGenderOptions = computed(() => usePetGenderOptions())

// 获取性别标签
const getGenderLabel = (gender: string) => {
  const genderOption = petGenderOptions.value.find((g: any) => g.value === gender)
  return genderOption?.label || '未知'
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPets()
})
</script>
